package com.ktjiaoyu.cond;

// 注意：Condition接口要导入spring框架的，不要导入错了

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;

@Target({ElementType.TYPE, ElementType.METHOD}) // 适用于类和方法
@Retention(RetentionPolicy.RUNTIME)
public @interface ConditionOnPropertyEnable {
    // 当配置文件中对应属性值为true时，则需要创建bean
    String enableProperty();

    /**
     * 实现了Condition接口，可以判断是否需要注册被标注的Bean
     */
    public class OnEnableCondition implements Condition {
        private static final Logger LOGGER =
                LoggerFactory.getLogger(OnEnableCondition.class);

        @Override
        public boolean matches(ConditionContext context,
                               AnnotatedTypeMetadata metadata) {
            // 获取元数据中被标记的@ConditionOnPropertyEnable注解的所有配置值
            Map<String, Object> attrs = metadata.getAnnotationAttributes(
                    ConditionOnPropertyEnable.class.getName());
            // 获取到注解定义的enableProperty的值
            String enableProperty = (String) attrs.get("enableProperty");
            LOGGER.info("当前读取到属性名称：enableProperty = {}",
                    enableProperty);
            // 从环境中获取properties文件对应配置的属性值
            String propertyValue = context.getEnvironment()
                    .getProperty(enableProperty);
            LOGGER.info("从配置文件中获取属性值：{} = {}",
                    enableProperty, propertyValue);
            // 是否需要注册
            Boolean needRegister = Boolean.valueOf(propertyValue);
            LOGGER.info("标注的Bean是否需要注册： {}", needRegister);
            // 返回boolean值，如果为true，则会创建bean对象
            return needRegister;
        }
    }
}
